package com.tianyu.common;

import com.alibaba.fastjson2.JSONObject;

import java.nio.charset.StandardCharsets;
import java.security.*;
import java.util.Base64;
import javax.crypto.Cipher;

public class RSAEncryptionExample {

    public static void main(String[] args) throws Exception {
        final long s = System.currentTimeMillis();
        // 1. 生成RSA密钥对
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(2048); // 可以指定密钥长度，如2048位
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        PublicKey publicKey = keyPair.getPublic();
        PrivateKey privateKey = keyPair.getPrivate();

        // 获取公钥并转换为Base64字符串
        byte[] publicKeyBytes = publicKey.getEncoded();
        String publicKeyString = Base64.getEncoder().encodeToString(publicKeyBytes);

        // 获取私钥并转换为Base64字符串
        byte[] privateKeyBytes = privateKey.getEncoded();
        String privateKeyString = Base64.getEncoder().encodeToString(privateKeyBytes);
        JSONObject.of("rsaPublic", publicKeyString,"rsaPrivate", privateKeyString);
        final long e = System.currentTimeMillis();
        System.out.println(e-s);
        // 输出结果
//        System.out.println("Public Key: " + publicKeyString);
//        System.out.println("Private Key: " + privateKeyString);

        // 2. 加密字符串
        String originalString = "Hello, RSA Encryption!";
        byte[] encryptedBytes = encrypt(originalString, publicKey);
        String encryptedString = Base64.getEncoder().encodeToString(encryptedBytes);
        System.out.println("Encrypted String: " + encryptedString);

        // 3. 解密字符串（可选）
        byte[] decryptedBytes = decrypt(encryptedBytes, privateKey);
        String decryptedString = new String(decryptedBytes);
        System.out.println("Decrypted String: " + decryptedString);
    }

    public static byte[] encrypt(String str, PublicKey publicKey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        return cipher.doFinal(str.getBytes(StandardCharsets.UTF_8));
    }

    public static byte[] decrypt(byte[] encryptedBytes, PrivateKey privateKey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        return cipher.doFinal(encryptedBytes);
    }
}